import { resolve } from 'node:path'
import process from 'node:process'
import type { ConfigEnv } from 'vite'
import { loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJSX from '@vitejs/plugin-vue-jsx'
import viteCompression from 'vite-plugin-compression'
import { visualizer } from 'rollup-plugin-visualizer'
import { ENV_CONFIG } from './src/config'

export default ({ mode }: ConfigEnv) => {
  console.log('🚀 ~ ENV:', mode, ENV_CONFIG[mode])
  return {
    base: ENV_CONFIG[mode].publicPath,
    build: {
      // 整理打包后的文件目录
      rollupOptions: {
        output: {
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          // 将不常变动的第三方库单独打包 有利于缓存
          manualChunks: {
            ant: ['ant-design-vue'],
            vue: ['vue', 'vue-router'],
            echarts: ['echarts'],
          },
        },
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          // javascriptEnabled: true,
          additionalData: `
            @import "@/assets/style/variable.less";
            @import "@/assets/style/mixin.less";
          `,
        },
      },
    },
    optimizeDeps: {
      include: ['ant-design-vue', 'vue', 'vue-router', 'echarts'],
    },
    plugins: [
      // unocss https://juejin.cn/post/7142466784971456548
      vue(),
      vueJSX(),
      // https://blog.csdn.net/Guojun19900715/article/details/131814200
      // TODO：应该要删除源文件
      viteCompression({
        algorithm: 'gzip',
        disable: false,
        ext: '.gz',
        threshold: 10240, // 对超过10k的数据进行压缩
        verbose: true,
        // deleteOriginFile: true, // 压缩后是否删除压缩源文件
      }),
      visualizer({
        emitFile: false,
        filename: 'report.html', // 分析图生成的文件名
        open: true, // 如果存在本地服务端口，将在打包后自动展示
      }),
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
    server: {
      open: true,
      port: 5174,
      proxy: {
        [ENV_CONFIG[mode].baseApi]: {
          changeOrigin: true,
          target: ENV_CONFIG[mode].host,
          secure: false, // 告诉代理不要验证目标服务器的证书的安全性,这在生产环境中是非常不安全的做法，仅适用于开发环境下的临时测试
          // rewrite: path => path.replace(new RegExp(`^${ENV_CONFIG[mode].baseApi}`), ''),
        },
      },
    },
  }
}
